# @Time : 2020/10/13 14:10 
# @Author : Michael
import Preprocess
import The_dial_to_match
import cv2 as cv
import numpy as np
import color_discrimination
from matplotlib import pyplot as plt


image_path1 = "2/1.jpg"
image_path2 = "2/2.jpg"

image_path3 = "3/1.jpg"
image_path4 = "3/2.jpg"

image_path5 = "1/1.jpg"
image_path6 = "1/2.jpg"

image_path7 = "4/1.jpg"
image_path8 = "4/2.jpg"

image_path9 = "6/1.png"
image_path10 = "6/2.jpg"

# image_path = "5/bluescene.jpg"
image_path = "7/gauge-2.jpg"


def identify_the_pointer():
    MT = The_dial_to_match.MatchTemplates(image_path7, image_path8)
    # MT.Resize(1, None, 0.7, 0.7)
    # MT.Resize(2, None, 0.9, 0.9)

    MT.Gray()
    wrap, out2 = MT.SHomography()

    if wrap is None:
        exit(999)
    P1 = Preprocess.METER(out2)
    # P1.Show('1')
    p2 = Preprocess.METER(wrap)
    p2.colorChange('gray')
    # p2.Show("3")
    p2.GaussianBlur(3)
    # p2.DoSobel(1)
    p2.OTSU_th()

    p2.Canny(0, 0, 3)
    p2.detect_circle()
    # p2.Show('?')
    rad = p2.get_pointer_rad()
    p2.draw_pointer(rad[1])
    # Preprocess.WhateverShow("out", p2.return_data('o'))
    images = [out2, p2.return_data('p'), p2.return_data('o')]
    for i in range(len(images)):
        images[i] = cv.cvtColor(images[i], cv.COLOR_BGR2RGB)
    for i in range(3):
        plt.subplot(1, 3, i + 1), plt.imshow(images[i])
        plt.title(i)
        plt.xticks([]), plt.yticks([])
    plt.show()


def test_color_change():

    red = color_discrimination.color_trace(image_path, "blue")
    a = Preprocess.METER(red)
    a.Show("red")


def trace_color_in_video():
    cap = cv.VideoCapture(0)
    while True:
        ret, frame = cap.read()
        out = color_discrimination.color_trace(frame, "red")
        cv.imshow('frame', out)
        if cv.waitKey(1) == 27:
            break
    cap.release()
    cv.destroyAllWindows()


if __name__ == '__main__':
    identify_the_pointer()
    # test_color_change()
    # trace_color_in_video()
